package no.saiboten.drumcalendar.interceptor;

import java.util.logging.Logger;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import no.saiboten.drumcalendar.user.CalendarUser;
import no.saiboten.drumcalendar.user.CalendarUserService;
import no.saiboten.drumcalendar.user.LoggedInRequestHolder;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

@Component
public class SecurityInterceptor extends HandlerInterceptorAdapter implements HandlerInterceptor {

	final Logger LOGGER = Logger.getLogger(SecurityInterceptor.class.getName());

	@Autowired
	CalendarUserService userService;

	UserService googleUserService;

	public SecurityInterceptor() {
		googleUserService = UserServiceFactory.getUserService();
	}

	@Autowired
	private LoggedInRequestHolder loggedIn;

	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
		if (request.getUserPrincipal() != null) {
			LOGGER.fine("User is logged in!");
			loggedIn.setLoggedIn(true);
			CalendarUser user = userService.getUser(request.getUserPrincipal().getName());
			if (user == null) {
				LOGGER.fine("User does not exist in db. Creating user in db!");
				user = new CalendarUser();
				user.setUserName(request.getUserPrincipal().getName());
				userService.putUser(user);
			}

			loggedIn.setCalendarUser(user);

		}
		return true;
	}
}
